/**
 * 催办弹出框
 */
import { Button, Input, Form, Modal, Select } from "antd";
import { forwardRef, useImperativeHandle, useState, useRef, useLayoutEffect, useEffect } from "react";
import request from "../../framework/common/utils/request";
import { useForm } from "../../framework/common/context/metadata-context";
import { message } from "antd";
import { globalModule } from "../../approval/index.js";
const { TextArea } = Input;

export default forwardRef(function ({}, ref) {
  const { data: tplData } = useForm().root;
  const [isVisible, setIsVisible] = useState(false);
  function showModal() {
    setIsVisible(true);
  }
  useImperativeHandle(ref, () => {
    return {
      showModal,
    };
  });
  return <>{isVisible && <ModalContent tplData={tplData} isVisible={isVisible} setIsVisible={setIsVisible}></ModalContent>}</>;
});

const ModalContent = function ({ isVisible, setIsVisible, tplData }) {
  const [form] = Form.useForm();
  const [btnLoading, setBtnLoading] = useState(false);

  //获取当前步骤的审批人
  let urge_name = tplData.urge_nodes || [];
  let urge_ids = []; //当前审批责任人id
  let urge_users = {}; //当前审批责任人名称
  urge_name = urge_name
    .map(function (item) {
      urge_ids.push(item.node_id);
      urge_users[item.auditor_id] = item.auditor_name;
      return item.auditor_name;
    })
    .join(",");

  useEffect(() => {
    request({
      url: "/systemsettings/message-mgr/ajax-get-reminder-subject", //设置默认催办意见
      method: "GET",
      data: {
        prc_name: tplData.ProcessInfo.Title,
        proc_id: tplData.ProcessInfo.ProcessGuid,
      },
      noTip: true//请求错误时，axios不展示公共错误
    })
      .then(function (result) {
        if (result.code == 1) {
          form.setFieldsValue({
            subject: result.data,
          }); //设置默认传阅意见
        } else {
          message.error(result.message);
        }
      })
      .catch(function () {});
  }, []);

  function handleOk() {
    setBtnLoading(true);

    form.validateFields()
      .then((values) => {
        let formData = form.getFieldsValue();

        var sendData = {
          subject: formData.subject, //催办内容
          node_ids: urge_ids,
          auditors: urge_users,
          proc_id: tplData.ProcessInfo.ProcessGuid,
        };

        setBtnLoading(true);
        request({
          url: "/flowinstance/approval/ajax-do-reminder?prc_name=" + tplData.ProcessInfo.Title,
          method: "POST",
          data: sendData,
          noTip: true//请求错误时，axios不展示公共错误
        })
          .then(function (result) {
            setBtnLoading(false);
            if (result.code == 1) {
              message.success("催办成功");
              setIsVisible(false);
              globalModule.refreshParentWindow({
                tplData: tplData,
                approveType: "Urgent",
              }); //催办后回调刷新业务系统的方法
              setTimeout(function () {
                window.location.href = window.location.href;
              }, 602);
            } else {
              if (result.code == 30063) {
                message.error(result.message);
                return;
              }
              message.error(result.message);
            }
          })
          .catch(function () {
            setBtnLoading(false);
            message.error("催办失败");
          });
      })
      .catch((errorInfo) => {
        setBtnLoading(false);
        return;
      });

    // form.validateFields(function (errors, values) {
    //   if (errors) {
    //     //如果存在校验不通过，不做请求
    //   }
    // });
  }

  const handleCancel = () => {
    setIsVisible(false);
  };

  // const { getFieldDecorator } = form;

  //表单对齐方式
  const formLayout = "horizontal";
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  return (
    <Modal
      centered={true}
      title="催办"
      width={600}
      visible={isVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      footer={[
        <Button key="back" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={btnLoading} onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form 
        form={form}
        labelAlign={"left"}
        colon={false}
        layout={formLayout}
      >
        <Form.Item
          label="当前责任人"
          name="urgeName"
          initialValue={urge_name}
          rules={[
            {
              required: true,
              message: "请录入催办内容",
            },
          ]}
          {...formItemLayout}
        >
          <div className="pl-2">{urge_name}</div>
        </Form.Item>
        <Form.Item
          label="消息内容"
          name="subject"
          initialValue=""
          rules={[
            {
              required: true,
              message: "请录入催办内容",
            },
          ]}
          {...formItemLayout}
        >
          <TextArea showCount={true} rows="8" maxLength={1000} placeholder="请录入催办内容"></TextArea>
        </Form.Item>
      </Form>
    </Modal>
  );
};
